const path = require("path")
const vscode = require('vscode');
const utils = require('./utils')
require('fast-text-encoding')
const {syncProjectStructureFromFile, initiallizeProjectStructure}=require('./projectStructure');
const {CONFIGARATION_FILE_NAME}=require('./constants')

let panel, disposable, courseJson;

async function activate(context) {
	const {
		extensionPath,
	} = context;
	const {
		workspace: {
			workspaceFolders,
			fs
		},
		Uri
	} = vscode


	const getTitle = isCoursePage => {
		if(isCoursePage){
			return "课程配置编辑器"
		}else{
			return "在线镜像"
		}
	}

	const startWebview = (isCoursePage = true) => {
		const columnToShowIn = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
		if (panel) {
			panel.reveal(columnToShowIn);
		} else {
			panel = vscode.window.createWebviewPanel(
				getTitle(isCoursePage),
				getTitle(isCoursePage),
				vscode.ViewColumn.One, {
					enableScripts: true,
					retainContextWhenHidden: true
				}
			);
		}

		// 获取磁盘上的资源路径
		const scriptPathOnDisk = vscode.Uri.file(
			path.join(extensionPath, "webview", "index.js")
		);
		const cssPathOnDisk = vscode.Uri.file(
			path.join(extensionPath, "webview", "index.css")
		);

		// 获取在webview中使用的特殊URI
		const scriptUri = panel.webview.asWebviewUri(scriptPathOnDisk);
		const cssUri = panel.webview.asWebviewUri(cssPathOnDisk);

		//获取course.json
		const openPath = vscode.Uri.file(
			path.join(workspaceFolders[0].uri.path, 'course.json')
		);

		vscode.workspace.openTextDocument(openPath).then(doc => {
			const text = doc.getText();
			courseJson = JSON.parse(text)
			

			if(isCoursePage){
				panel.webview.postMessage({
					command: 'load',
					data: courseJson
				});
			}else{
				panel.webview.postMessage({
					command: 'run',
					data: courseJson
				});
			}

		});
		panel.webview.html = `  
        <!DOCTYPE html>
        <html lang="zh">
          <head>
            <meta charset="utf-8" />
            <link href="${cssUri}"  rel="stylesheet">
          </head>
          <body>
			<div id="root"></div>
			<script src="${scriptUri}"></script>
			
          </body>
          </html>
        `;
		//gosave
		panel.webview.onDidReceiveMessage(
			message => {
				switch (message.command) {
					case 'save':{
						const encoder = new TextEncoder()
						const encodedData = encoder.encode(JSON.stringify(message.data,null,2))

						let filePath=path.join(workspaceFolders[0].uri.path, 'course.json')
						fs.writeFile(Uri.file(filePath),encodedData);
						vscode.window.showInformationMessage('保存成功！');
						return;
					};
					case 'openDoc': {
						//在浏览器中打开官方文档
						vscode.env.openExternal(vscode.Uri.parse('http://gitcourse-io.kfcoding.com/getting-started/quick/'));
						return;
					}
					case 'openExternalUrl' //TODO:将openDoc合并
					: {
						vscode.env.openExternal(vscode.Uri.parse(message.data));
						return;
					}
				}
			},
			undefined,
			context.subscriptions
		);
		panel.onDidDispose(
			() => {
				panel = null
			},
			null,
			context.subscriptions
		  );
	}
	disposable = vscode.commands.registerCommand("gitcourse-maker.start", startWebview);
	context.subscriptions.push(disposable);


	disposable = vscode.commands.registerCommand("gitcourse-maker.switch", () => {
		if(panel){
			if(panel.active){
				const openPath = vscode.Uri.file(
					path.join(workspaceFolders[0].uri.path, 'course.json')
				);
		
				vscode.workspace.openTextDocument(openPath).then(doc => {
					vscode.window.showTextDocument(doc)
				});
			}else{
				if(panel.title != getTitle(true)){
					panel.title = getTitle(true)
					panel.dispose()
				}
				startWebview(true)
			}
		}else{
			startWebview(true)
		}
	});
	context.subscriptions.push(disposable);

	disposable = vscode.commands.registerCommand("gitcourse-maker.syncProjectStructure", ()=> {
		syncProjectStructureFromFile(CONFIGARATION_FILE_NAME);
	})
	context.subscriptions.push(disposable);

	disposable = vscode.commands.registerCommand("gitcourse-maker.initializeProject", ()=> {
		initiallizeProjectStructure(extensionPath);
	})
	context.subscriptions.push(disposable);


	disposable = vscode.commands.registerCommand("gitcourse-maker.run", ()=> {
		if(panel){
			if(panel.title == getTitle(true)){
				//当前是coursepage
				panel.title = getTitle(false)
				startWebview(false)
			}else if(! panel.active ){
				//是runPage 不在当前窗口
				startWebview(false)
			}else{
				//runpage 在当前窗口
			}
		}else{
			startWebview(false)
		}
	})

	context.subscriptions.push(disposable);

}


function deactivate() {

}

module.exports = {
	activate,
	deactivate
}